# feed sentences to the GrammarUtil
# check if every sentence can be parsed and every word is covered by the Grammar
# create logic expression from each sentence

# add some pre-defined expression

# enter a question
# convert the question to a logic expression

# solve
import nltk

class GrammarUtil:
    
    def __init__(self, grammar_location=None, trace=0):
        self.grammar_location = grammar_location # grammar location
        #self.parser = nltk.parse.load_earley(self.grammar_location, trace=trace)
        self.trace = trace
        self.initParser()
    
    def initParser(self):
        self.parser = nltk.parse.load_parser(self.grammar_location, trace=self.trace)
    
    def grammar(self):
        """
            returns the grammar used by this grammar
        """
        return self.parser.grammar()
    
    def parseExpr(self, expr):
        """
            Parses the expression string and returns a Logic Expression object 
        """
        lp = nltk.LogicParser()
        logic_expression = lp.parse(expr)       
        return logic_expression 
    
    def convertSentToExpr(self, sentence):
        """
            returns a symantic logic expression generated by the grammar
        """
        trees = nltk.sem.batch_parse([sentence], self.grammar_location, trace=self.trace)
        parse_tree1 = trees[0][0]
        semrep = nltk.sem.root_semrep(parse_tree1)
        return semrep      
    
    def isSentCovered(self, sentence):
        """
            returns true if the sentence can be parsed by the grammar
        """
        inputs = [sentence]
        tokens = sentence.split()
        try:
            self.grammar().check_coverage(tokens)
        except ValueError, e:
            return False
        #if not self.grammar().check_coverage(tokens):
        #    return False
         
        totaltrees = 0
        for syntrees in nltk.sem.batch_parse(inputs, self.grammar_location, trace=self.trace):
            if self.trace > 0:
                print syntrees
            totaltrees = totaltrees + len(syntrees)
        return totaltrees > 0 # we should minimally have one parse tree
        #return [[(syn, nltk.sem.root_semrep(syn, start=start)) for syn in syntrees]
        #    for syntrees in nltk.sem.batch_parse(inputs, self.grammar_location, trace=5)]
        


        